package com.lee.mq.mqserver.datacenter;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-10-21
 * Time: 12:46
 */

import com.lee.mq.MqApplication;
import com.lee.mq.mqserver.core.Binding;
import com.lee.mq.mqserver.core.Exchange;
import com.lee.mq.mqserver.core.ExchangeType;
import com.lee.mq.mqserver.core.MSGQueue;
import com.lee.mq.mqserver.mapper.MetaMapper;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 整合数据库操作
 */
public class DataBaseManager {

    private MetaMapper metaMapper;

    // 数据库初始化
    public void init() {
        // 手动获取 MetaMapper
        metaMapper = MqApplication.context.getBean(MetaMapper.class);

        if (!checkDBExists()) {
            // 数据库不存在就建库建表
            // 1.创建 data 目录
            // 建库操作并不需要手动执行. (不需要手动创建 meta.db 文件)
            // 首次执行这里的数据库操作的时候, 就会自动的创建出 meta.db 文件来 (MyBatis 帮我们完成的)
            File dataDir = new File("./data");
            dataDir.mkdirs();
            // 2.创建数据表
            createTable();
            // 3.插入默认数据
            createDefaultData();
            // 4.打印日志
            System.out.println("[DataBasesManager] 数据库初始化完成!");
        } else {
            // 数据库已存在，打印日志即可
            System.out.println("[DataBaseManager] 数据库已存在!");
        }
    }

    /**
     * 删除数据库
     */
    public void deleteDB() {
        File file = new File("./data/meta.db");
        boolean ret = file.delete();
        if (ret) {
            System.out.println("[DataBaseManager] 数据库删除成功!");
        } else {
            System.out.println("[DataBaseManager] 数据库删除失败!");
        }
        // 使用delete删除目录时，需要保证目录是空的
        File file1 = new File("./data");
        ret = file1.delete();
        if (ret) {
            System.out.println("[DataBaseManager] 数据库目录删除成功!");
        } else {
            System.out.println("[DataBaseManager] 数据库目录删除失败!");
        }
    }

    /**
     * 判断名为 meta.db 数据库是否已存在
     * @return ture 已存在；false 不存在
     */
    private boolean checkDBExists() {
        File file = new File("./data/meta.db");
        if (file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * 建表方法.
     */
    private void createTable() {
        metaMapper.createExchangeTable();
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
        System.out.println("[DataBaseManager] 创建完成!");
    }

    /**
     * 给数据库表添加默认数据
     */
    private void createDefaultData() {
        // 创建一个默认的交换机（参考RabbitMQ）
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        int row = metaMapper.insertExchange(exchange);
        if (row != 1) {
            System.out.println("[DatabaseManager] 创建初始数据失败!");
        } else {
            System.out.println("[DatabaseManager] 创建初始数据完成!");
        }
    }

    // 核心表的增删查
    public int insertExchange(Exchange exchange) {
        return metaMapper.insertExchange(exchange);
    }
    public int deleteExchange(String exchangeName) {
        return metaMapper.deleteExchange(exchangeName);
    }
    public List<Exchange> selectAllExchanges() {
        return metaMapper.selectAllExchanges();
    }

    public int insertQueue(MSGQueue msgQueue) {
        return metaMapper.insertQueue(msgQueue);
    }
    public int deleteQueue(String queueName) {
        return metaMapper.deleteQueue(queueName);
    }
    public List<MSGQueue> selectAllQueues() {
        return metaMapper.selectAllQueues();
    }

    public int insertBinding(Binding binding) {
        return metaMapper.insertBinding(binding);
    }
    public int deleteBinding(Binding binding) {
        return metaMapper.deleteBinding(binding);
    }
    public List<Binding> selectAllBindings() {
        return metaMapper.selectAllBindings();
    }
}
